<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/17
 * Time: 13:15
 */

namespace common\business\upload;

use common\consts\CommonResources;
use common\models\EmployeePhoto;
use common\models\kingdee\HrPersonPhoto;
use common\models\kingdee\Person;
use common\result\ActionResult;
use Yii;
use yii\db\Query;

class UploadHelper
{
//    public static function uploadEmployeePhoto($personId){
//        $person = Person::findOne($personId);
//
//        if (!$person){
//            $failReason = CommonResources::ACTION_NAME_MODEL_FAIL('Upload', 'Employee Photo', $personId);
//            $errMsg = CommonResources::ACTION_FAIL_MSG('Upload', 'File', $failReason);
//            Yii::error($errMsg);
//            return new ActionResult(false, $errMsg);
//        }
//
//        $employee_number = $person->FNUMBER;
//        $employee_name = $person->FNAME_L2;
//
//        $personPhoto = HrPersonPhoto::findOne([
//            'FPERSONID' => $personId
//        ]);
//        if (!$personPhoto){
//            $failReason = CommonResources::ACTION_NAME_MODEL_FAIL_WITH_REASON('Get', 'Person Content', $personId, 'PersonPhoto Not Found');
//            $errMsg = CommonResources::ACTION_FAIL_MSG('Upload', 'File', $failReason);
//            Yii::error($errMsg);
//            return new ActionResult(false, $errMsg);
//        }
//
//        $employeePhoto = EmployeePhoto::findOne([
//            'employee_number' => $employee_number
//        ]);
//        if (!$employeePhoto){
//            $newObj = new EmployeePhoto();
//            $newObj->employee_number = $employee_number;
//            $newObj->employee_name = $person->FNAME_L2;
//            $newObj->image_height = $personPhoto->FSOURCEIMAGEHEIGHT;
//            $newObj->image_width = $personPhoto->FSOURCEIMAGEWIDTH;
//
//            $fileExtension = 'jpg';
//            $fileName = sprintf('%s_%s.%s', $employee_number, $employee_name, $fileExtension);
//            $fileNameEncoded = iconv('utf-8', 'GBK//TRANSLIT//IGNORE', $fileName);
//
//            $filePath = Yii::getAlias('@backend/runtime/employee_photos/');
//            $fileFullPath = $filePath.$fileName;
//
//            $newObj->image_url = $fileFullPath;
//        }
//
//
//    }


    /**
     * @param $person Person
     * @param $personPhoto HrPersonPhoto
     * @return bool
     */
    public static function createOrUpdateEmployeePhoto($person, $personPhoto = null){
        if (!$personPhoto){
            $personPhoto = HrPersonPhoto::findOne([
                'FPERSONID' => $person->FID
            ]);
            if (!$personPhoto) return false;
        }

        $employee_number = $person->FNUMBER;
        $employee_name = $person->FNAME_L2;
        $getPath = sprintf('employee/get-photo/?number=', $employee_number);

//        mysqli_fetch_assoc()
        $imageData = (new Query())->from('T_HR_PERSONPHOTO')->select('FIMAGEDATA')->andFilterWhere([
            'FPERSONID' => $person->FID
        ])->one(HrPersonPhoto::getDb());
        $imageData = stream_get_contents($personPhoto->FIMAGEDATA);

//        $imageData = file_get_contents($personPhoto->FIMAGEDATA);
//        if( ocifetchinto($personPhoto->FIMAGEDATA, $result, OCI_ASSOC+OCI_RETURN_LOBS) )
//        {
//            $imageData = $result;
//        }

        $employeePhoto = EmployeePhoto::findOne([
            'employee_number' => $employee_number
        ]);
        if (!$employeePhoto){
            $newObj = new EmployeePhoto();
            $newObj->employee_number = $employee_number;
            $newObj->employee_name = $employee_name;
            $newObj->image_height = $personPhoto->FSOURCEIMAGEHEIGHT;
            $newObj->image_width = $personPhoto->FSOURCEIMAGEWIDTH;
            $newObj->image_data = $imageData;

            $fileExtension = 'jpg';
            $fileName = sprintf('%s_%s.%s', $employee_number, $employee_name, $fileExtension);
            $fileNameEncoded = iconv('utf-8', 'GBK//TRANSLIT//IGNORE', $fileName);

//            $filePath = Yii::getAlias('@backend/runtime/employee_photos/');

//            $fileFullPath = $filePath.$fileName;

            $newObj->image_url = $getPath;

            $saveSuccess = $newObj->save();
            if (!$saveSuccess){
                $failReason = CommonResources::ACTION_NAME_MODEL_FAIL('Create', 'EmployeePhoto', $newObj->employee_name);
                $errMsg = CommonResources::ACTION_FAIL_MSG('Create', 'EmployeePhoto', $failReason);
                Yii::error($errMsg);
            }
            return $saveSuccess;
        }
        else {
            $employeePhoto->image_height = $personPhoto->FSOURCEIMAGEHEIGHT;
            $employeePhoto->image_width = $personPhoto->FSOURCEIMAGEWIDTH;
            $employeePhoto->image_url = $getPath;
            return $employeePhoto->save();
        }
    }

    public static function uploadEmployeePhotoFileToBackend($employee_number, $employee_name, $fileExtension, $fileContent){
        $filePath = Yii::getAlias('@backend/runtime/employee_photos/');

        $fileName = sprintf('%s_%s.%s', $employee_number, $employee_name, $fileExtension);
        $fileName = iconv('utf-8', 'GBK//TRANSLIT//IGNORE', $fileName);

//        $saveSuccess = self::createOrUpdateEmployeePhoto($person);
//        echo $saveSuccess;
        return self::uploadFile($filePath, $fileName, $fileContent);
    }

    public static function uploadEmployeePhotoFileToApi($employee_number, $employee_name, $fileExtension, $fileContent){
        $filePath = Yii::getAlias('@api/web/images/employee_photos/');
        $fileName = sprintf('%s_%s.%s', $employee_number, $employee_name, $fileExtension);
        $fileName = iconv('utf-8', 'GBK//TRANSLIT//IGNORE', $fileName);
        return self::uploadFile($filePath, $fileName, $fileContent);
    }

    public static function uploadEmployeePhotoFile($filePath, $employee_number, $employee_name, $fileExtension, $fileContent){
//        $filePath = Yii::getAlias('@backend/runtime/employee_photos/');

        $fileName = sprintf('%s_%s.%s', $employee_number, $employee_name, $fileExtension);
        $fileName = iconv('utf-8', 'GBK//TRANSLIT//IGNORE', $fileName);

//        $saveSuccess = self::createOrUpdateEmployeePhoto($person);
//        echo $saveSuccess;
        return self::uploadFile($filePath, $fileName, $fileContent);
    }

    public static function uploadFile($filePath, $fileName, $fileContent) {

        // 目录不存在则创建
        if (!is_dir($filePath)) {
            if (!mkdir($filePath)) {
                $failReason = CommonResources::ACTION_NAME_MODEL_FAIL('Create', 'Folder', $filePath);
                $errMsg = CommonResources::ACTION_FAIL_MSG('Upload', 'File', $failReason);
                Yii::error($errMsg);
                return new ActionResult(false, $errMsg);
            }
        }

        $fileFullPath = $filePath.$fileName;

        //将数据写入file文件3步骤:创建打开--写入数据--保存关闭
        //1.打开文件并选择模式（只读、只写、读写）
        $fp = fopen($fileFullPath,'ab');
        if(!$fp){
            $failReason = CommonResources::ACTION_NAME_MODEL_FAIL('Create', 'File', $fileFullPath);
            $errMsg = CommonResources::ACTION_FAIL_MSG('Upload', 'File', $failReason);
            Yii::error($errMsg);
            return new ActionResult(false, $errMsg);
        }
//        写入数据
        fwrite($fp,$fileContent);
        flock($fp,LOCK_UN);
        fclose($fp);
        return new ActionResult(true, CommonResources::ACTION_NAME_MODEL_SUCCESS('Create', 'File', $fileName));
    }
}